﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using mscook.mvc.Filters;
using mscook.mvc.Models;
using mscook.core.services;
using mscook.mvc.Core;
using mscook.core.domain;
using System.Security.Principal;
using mscook.core;
using mscook.core.repositories;
using mscook.core.components;
using mscook.Alipay;
using mscook.core.enumType;
using System.Collections.Specialized;

namespace mscook.mvc.Controllers
{

    [UserAuthorizeAttribute(Roles = "admin,editor,systemUser")]
    public class CenterController : BaseController
    {
        //
        // GET: /Center/
        private ILoginUserService iLoginUserService;
        private IPresentRepository iPresentRepository = UnityHelper.UnityToT<IPresentRepository>();
        private IMagazineRepository iMagazineRepository = UnityHelper.UnityToT<IMagazineRepository>();
        private ICookBookRepository iCookBookRepository = UnityHelper.UnityToT<ICookBookRepository>();
        private ILoginUserOfPresentRepository iLoginUserOfPresentRepository = UnityHelper.UnityToT<ILoginUserOfPresentRepository>();
        private IBonusOrderRepository iBonusOrderRepository = UnityHelper.UnityToT<IBonusOrderRepository>();
        private IBonusBuyRepository iBonusBuyRepository = UnityHelper.UnityToT<IBonusBuyRepository>();

        private IPurchasedThingRepository iPurchasedThingRepository = UnityHelper.UnityToT<IPurchasedThingRepository>();
        public CenterController(IActionBonusSettingService actionBonusSettingService, IResourceBonusSettingService resourceBonusSettingService, ILoginUserService loginUserService)
            : base(actionBonusSettingService, resourceBonusSettingService, loginUserService)
        {
            this.iLoginUserService = loginUserService;
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Index()
        {
            CenterBaseModel centerModel = new CenterBaseModel();
            centerModel.LoginUser = CurrentUser;


            ViewBag.MagazineCount = iPurchasedThingRepository.GetHasPurchased(CurrentUser, PurchasedCategory.Magazine);
            ViewBag.CookBookCount = iPurchasedThingRepository.GetHasPurchased(CurrentUser, PurchasedCategory.CookBook);
            return View(centerModel);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(string Name, string Tel, string Description)//不建议采用更新Model
        {

            LoginUser LoginUser = base.CurrentUser;
            LoginUser.Name = Name;
            LoginUser.Tel = Tel;
            LoginUser.Description = Description;

            iLoginUserService.SaveOrUpdate(LoginUser);


            return View(LoginUser);
        }

        [HttpGet]
        public ActionResult ChangePassword()
        {
            ChangePasswordModel changePasswordModel = new ChangePasswordModel();
            changePasswordModel.LoginUser = CurrentUser;
            return View(changePasswordModel);
        }
        [ValidateAntiForgeryToken]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ChangePassword(ChangePasswordModel changePasswordModel)
        {
            string message = string.Empty;
            if (ModelState.IsValid)
            {
                if (changePasswordModel.IsEqual())
                {
                    if (CurrentUser.Password.Equals(changePasswordModel.OldPaasword))
                    {
                        CurrentUser.Password = changePasswordModel.NewPassword;
                        iLoginUserService.SaveOrUpdate(CurrentUser);
                        message = "密码修改成功";
                    }
                    else
                    {
                        message = "原始密码输入错误";
                    }
                }
                else
                {
                    message = "两次所填新密码不相同";
                }

            }
            else
            {
                message = "新密码不符合规范";
                //ModelState.AddModelError("", "提供的用户名或密码不正确。");
            }
            changePasswordModel.LoginUser = CurrentUser;
            ModelState.AddModelError("", message);
            return View(changePasswordModel);

        }

        [HttpGet]

        public ActionResult Info()
        {
            CenterInfoModel centerModel = new CenterInfoModel();
            centerModel.InitLoginUser(CurrentUser);
            return View(centerModel);
        }

        [HttpPost]

        public ActionResult Info(CenterInfoModel centerModel)
        {

            if (ModelState.IsValid)
            {
                CurrentUser.Address = centerModel.Address;
                CurrentUser.Tel = centerModel.Tel;
                CurrentUser.Name = centerModel.Name;
                CurrentUser.SelfPage = centerModel.SelfPage;
                iLoginUserService.SaveOrUpdate(CurrentUser);

                centerModel.InitLoginUser(CurrentUser);
                ModelState.AddModelError("", "个人信息修改成功");
            }
            else
            {
                ModelState.AddModelError("", "所填信息不符合要求");
            }

            return View(centerModel);
        }

        [HttpGet]

        public ActionResult Magazine()
        {
            CenterMagazineModel centerMagazineModel = new CenterMagazineModel();
            centerMagazineModel.LoginUser = CurrentUser;

            centerMagazineModel.MagazineList = iMagazineRepository.GetAllByIds(CurrentUser.PurchasedThingIds(PurchasedCategory.Magazine));

            return View(centerMagazineModel);
        }

        [HttpGet]
        public ActionResult CookBook()
        {
            CenterCookBookModel cookBookModel = new CenterCookBookModel();
            cookBookModel.LoginUser = CurrentUser;
            cookBookModel.CookBookList = iCookBookRepository.GetAllByIds(CurrentUser.PurchasedThingIds(PurchasedCategory.CookBook));
            return View(cookBookModel);

        }

        [HttpGet]

        public ActionResult Present()
        {
            CenterPresentModel cookPresentModel = new CenterPresentModel();
            cookPresentModel.LoginUser = CurrentUser;
            cookPresentModel.PresentLit = iPresentRepository.GetAll();
            return View(cookPresentModel);
        }

        [HttpPost]

        public JsonResult BuyPresent(CenterPresentModel model, string id)
        {
            mscook.mvc.Core.ValidateResult vr = new mscook.mvc.Core.ValidateResult() { IsSuccess = false, Message = "请填写正确格式信息" };
            Present present = iPresentRepository.Get(id);
            if (ModelState.IsValid && present != null)
            {
                ResourceBonusStrategy resourceBonusStrategy = new ResourceBonusStrategy(id, ResourceBonusSettings, CurrentUser, this.LoginUserService);
                if (CurrentUser != null)
                {
                    if (resourceBonusStrategy.SetBonus(true, model.Amount))
                    {
                        LoginUserOfPresent loginUserOfPresent = new LoginUserOfPresent() { Address = model.Address, Tel = model.Tel, Amount = model.Amount, LoginUser = CurrentUser, Present = present };
                        iLoginUserOfPresentRepository.SaveOrUpdate(loginUserOfPresent);
                        vr.IsSuccess = true;
                        vr.Message = "兑换成功，请等待美食之窗管理员与您确认";
                    }
                    else
                    {
                        vr.Message = "积分不足，请您获取积分后重试";
                    }

                }
            }
            return new JsonResult { Data = vr };
        }

        [HttpGet]

        public ActionResult BonusBuy()
        {
            CenterBounsBuyModel centerBounsBuyModel = new CenterBounsBuyModel();
            centerBounsBuyModel.LoginUser = CurrentUser;
            centerBounsBuyModel.Phone = CurrentUser.Tel;
            centerBounsBuyModel.BonusBuyList = iBonusBuyRepository.GetAllOrderByPrice();
            return View(centerBounsBuyModel);
        }

        [HttpPost]
        public ActionResult Alibuy(CenterBounsBuyModel centerBounsBuyModel, string bonusBuyId)
        {
            BonusBuy bonusBuy = iBonusBuyRepository.Get(bonusBuyId);

            if (ModelState.IsValid && bonusBuy!=null)
            {
                BonusOrder bonusOrder = new BonusOrder();
                bonusOrder.Price = bonusBuy.Price;
                bonusOrder.Bonus = bonusBuy.Bonus;
                bonusOrder.LoginUser = CurrentUser;
                bonusOrder.TelPhone = centerBounsBuyModel.Phone;
                iBonusOrderRepository.SaveOrUpdate(bonusOrder);

                SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
                sParaTemp.Add("partner", Config.Partner);
                sParaTemp.Add("_input_charset", Config.Input_charset.ToLower());
                sParaTemp.Add("service", "trade_create_by_buyer");
                sParaTemp.Add("payment_type", CenterBounsBuyModel.payment_type);
                sParaTemp.Add("notify_url", CenterBounsBuyModel.notify_url);
                sParaTemp.Add("return_url", CenterBounsBuyModel.return_url);
                sParaTemp.Add("seller_email", CenterBounsBuyModel.seller_email);
                sParaTemp.Add("out_trade_no", bonusOrder.OrederNumber);
                sParaTemp.Add("subject", CenterBounsBuyModel.subject);
                sParaTemp.Add("price", bonusBuy.Price.ToString());
                sParaTemp.Add("quantity", CenterBounsBuyModel.quantity);
                sParaTemp.Add("logistics_fee", CenterBounsBuyModel.logistics_fee);
                sParaTemp.Add("logistics_type", CenterBounsBuyModel.logistics_type);
                sParaTemp.Add("logistics_payment", CenterBounsBuyModel.logistics_payment);
                string sHtmlText = Submit.BuildRequest(sParaTemp, "get", "确认");
                return Content(sHtmlText);
            }
            return Content("");

        }

        public ActionResult AlibuyReturn(string out_trade_no, string trade_status)
        {
            CenterAlibuyModel centerAlibuyModel = new CenterAlibuyModel();
            centerAlibuyModel.LoginUser = CurrentUser;
            //SortedDictionary<string, string> sPara = GetRequestGet();
            // SortedDictionary<string, string> sPara = Notify.GetRequest(Request.QueryString);

            if (Notify.Verify(Request.QueryString))
            {
                centerAlibuyModel.BonusOrder = UpdateLoginUserBonus(out_trade_no, trade_status);
            }

            return View(centerAlibuyModel);
        }

        public ActionResult AlibuyNotify(string out_trade_no, string trade_status)
        {

            if (Notify.Verify(Request.Form))
            {
                UpdateLoginUserBonus(out_trade_no, trade_status);
                return Content("success");
            }
            return Content("fail");
        }
        private BonusOrder UpdateLoginUserBonus(string bonusOrderId, string trade_status)
        {
            BonusOrder bonusOrder = iBonusOrderRepository.GetByOrderNumber(bonusOrderId);
            if (bonusOrder != null && bonusOrder.OrderStatus != BonusOrderStatus.交易成功 && trade_status.ToUpper() == "TRADE_FINISHED")//此处进行业务逻辑处理,暂时假定钱已经打入卖家账户，不考虑其他状况
            {
                CurrentUser.Bonus += bonusOrder.Bonus;
                iLoginUserService.SaveOrUpdate(CurrentUser);
                bonusOrder.OrderStatus = BonusOrderStatus.交易成功;
                iBonusOrderRepository.SaveOrUpdate(bonusOrder);
            }

            return bonusOrder;
        }

       


    }
}
